import 'package:cloud_phone_manager/utils/CmdUtils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../data/Data.dart';
import '../provider/AdbCurrentChangeProvider.dart';
import '../provider/AdbDevicesProvider.dart';

class AppManager extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _AppManager();
}

class _AppManager extends State<AppManager> {
  List<AppInfo> _appInfo = [];
  List<AppInfo> _appInfoUser = [];
  List<AppInfo> _show = [];
  bool _isFilterSystem = false;
  bool _isInit = false;
  AdbCurrentChangeProvider? provider;
  TextEditingController tagController = TextEditingController();

  @override
  void initState() {
    super.initState();
    if (!_isInit) {
      _isInit = true;
      initList();
    }
  }


  void initList() {
    _appInfo.clear();
    _appInfoUser.clear();
    _show.clear();
    CmdUtils.deviceApps((success, error, process, successListener) {
      // debugPrint("应用列表：$success");
      List<String> array = success.split("\r\n");
      for (String item in array) {
        if (!item.contains(":")) {
          continue;
        }
        String pg =
            item.split(":")[1].trim().replaceAll("\r", "").replaceAll("\n", "");
        setState(() {
          _appInfo.add(AppInfo("_name", "_version", pg, true));
        });
      }
      debugPrint("长度：${_appInfo.length}");
      if (success == "DONE") {
        CmdUtils.deviceAppsUser((success, error, process, successListener) {
          debugPrint("用户列表为：" + success);
          List<String> array = success.split("\r\n");
          for (String item in array) {
            if (!item.contains(":")) {
              continue;
            }
            String pg = item
                .split(":")[1]
                .trim()
                .replaceAll("\r", "")
                .replaceAll("\n", "");
            setState(() {
              _appInfoUser.add(AppInfo("_name", "_version", pg, false));
            });
            int index = 0;
            List<int> indexArray = [];
            for (AppInfo app in _appInfo) {
              if (app.packageName == pg) {
                indexArray.add(index);
                debugPrint("存在相同的包名");
              }
              index++;
            }
            for (int inde in indexArray) {
              _appInfo.removeAt(inde);
            }
          }
          if(_isFilterSystem){
            _show.addAll(_appInfoUser);
          }else{
            _show.addAll(_appInfo);
            _show.addAll(_appInfoUser);
          }
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    if (provider == null) {
      provider = Provider.of<AdbCurrentChangeProvider>(context);
      debugPrint("注册监听");
      provider?.addListener(() {
        initList();
      });
    }
    return Container(
      alignment: Alignment.topLeft,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            margin: const EdgeInsets.fromLTRB(10, 0, 0, 0),
            child: Row(
              children: [
                const Text(
                  "用户",
                  style: TextStyle(fontWeight: FontWeight.bold),
                ),
                Checkbox(
                  value: _isFilterSystem,
                  onChanged: (bool? value) {
                    _show.clear();
                    setState(() {
                      _isFilterSystem = value ?? false;
                      if (_isFilterSystem) {
                        _show.addAll(_appInfoUser);
                      } else {
                        _show.addAll(_appInfo);
                      }
                    });
                  },
                ),
                TextButton(
                    onPressed: () {
                      initList();
                    },
                    child: const Text("刷新")),
                SizedBox(width: 300,height: 40,child: TextField(
                    keyboardType: TextInputType.text,
                    controller: tagController,
                    decoration: const InputDecoration(
                      labelText: '搜索包名',
                      border: OutlineInputBorder(),
                    ),onEditingComplete: (){
                      String input = tagController.text.toString();
                      List<AppInfo> tmpp = [];
                      tmpp.addAll(_appInfo);
                      tmpp.addAll(_appInfoUser);
                      List<AppInfo> tmp = [];
                      for(AppInfo item in tmpp){
                        if(item.packageName.contains(input)){
                          tmp.add(item);
                        }
                      }
                      _show.clear();
                      setState(() {
                        _show.addAll(tmp);
                      });
                },),)
              ],
            ),
          ),
          Expanded(
              child: ListView.builder(
            itemCount: _show.length,
            itemBuilder: (context, index) {
              return SizedBox(
                width: MediaQuery.of(context).size.width,
                child: Row(
                  children: [
                    Expanded(
                      flex: 8,
                      child: SizedBox(
                        child: ListTile(
                          leading: const Icon(Icons.apps),
                          title: Text(
                            _show[index].packageName,
                            style: const TextStyle(fontSize: 12),
                          ),
                          subtitle: Text(
                            _show[index].isSystem ? "系统" : "用户",
                            style: TextStyle(
                                color: _show[index].isSystem
                                    ? Colors.red
                                    : Colors.green),
                          ),
                          onTap: () {},
                          onLongPress: () {},
                        ),
                      ),
                    ),
                    TextButton(
                      child: const Text(
                        "启动",
                        style: TextStyle(fontSize: 15),
                      ),
                      onPressed: () =>
                          {CmdUtils.launchApp(_show[index].packageName)},
                    ),
                    TextButton(
                      child: const Text(
                        "停止",
                        style: TextStyle(fontSize: 15),
                      ),
                      onPressed: () =>
                          {CmdUtils.stopApp(_show[index].packageName)},
                    ),
                    TextButton(
                      child: const Text(
                        "卸载",
                        style: TextStyle(fontSize: 15),
                      ),
                      onPressed: () => {
                        CmdUtils.uninstallApp(_show[index].packageName),
                        setState(() {
                          _show.removeAt(index);
                        })
                      },
                    ),
                    TextButton(
                      child: const Text(
                        "清理",
                        style: TextStyle(fontSize: 15),
                      ),
                      onPressed: () =>
                          {CmdUtils.cleanAppData(_show[index].packageName)},
                    )
                  ],
                ),
              );
            },
          ))
        ],
      ),
    );
  }
}
